package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.UserLocationApi;
import com.tanhua.dubbo.server.api.VisitorsApi;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.pojo.Visitors;
import com.tanhua.dubbo.server.vo.UserLocationVo;
import com.tanhua.server.enums.SexEnum;
import com.tanhua.server.pojo.Question;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.NearUserVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.RecommendUserQueryParam;
import com.tanhua.server.vo.TodayBest;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class TodayBestService {


    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RecommendUserService recommendUserService;


    @Value("${tanhua.sso.default.user}")
    private Long defaultUser;

    @Value("${tanhua.sso.default.recommend.users}")
    private String defaultRecommendUsers;

    public TodayBest queryTodayBest(String token) {
        User user = UserThreadLocal.get();
        //获取今日佳人的id
        TodayBest todayBest = recommendUserService.queryTodayBest(user.getId());
        if (todayBest == null) {
            //给出默认的推荐用户
            todayBest = new TodayBest();
            todayBest.setId(defaultUser);
            todayBest.setFateValue(80L); //固定值
        }
        //补全个人信息
        UserInfo userInfo = userInfoService.queryUserInfoByUserId(todayBest.getId());
        if (null == userInfo) {
            return null;
        }
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
        todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
        todayBest.setAge(userInfo.getAge());

        return todayBest;
    }

    public PageResult queryRecommendation(String token, RecommendUserQueryParam params) {
        User user = UserThreadLocal.get();
        if (null == user) {
            //token非法或已经过期
            return null;
        }
        //查询MongoDB获取推荐用户的id集合
        Long userId = user.getId();
        List<RecommendUser> list = recommendUserService.queryRecommendation(userId, params.getPage(), params.getPagesize());
        PageResult pageResult = new PageResult();
        if (CollectionUtils.isEmpty(list)) {
            //没有查询到推荐的用户列表
            //使用默认推荐用户
            String[] recommendUserIds = defaultRecommendUsers.split(",");
            for (String recommendUserId : recommendUserIds) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(recommendUserId));
                recommendUser.setToUserId(userId);
                recommendUser.setScore(RandomUtils.nextDouble(70, 99));
                list.add(recommendUser);
            }
        }
        Set<Long> userIds = new HashSet<>();
        for (RecommendUser recommendUser : list) {
            userIds.add(recommendUser.getUserId());
        }
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(UserInfo::getUserId, userIds);
        /*if (StringUtils.isNotEmpty(params.getGender())) {
            //需要性别参数查询
            wrapper.eq(UserInfo::getSex, StringUtils.equals(params.getGender(), "man") ? 1 : 2);
        }
        if (StringUtils.isNotEmpty(params.getCity())) {
            //需要城市参数查询
            wrapper.like(UserInfo::getCity, params.getCity());
        }
        if (params.getAge() != null) {
            //设置年龄参数，条件：小于等于
            wrapper.le(UserInfo::getAge, params.getAge());
        }*/
        List<UserInfo> userInfos = userInfoService.queryRecommendationInfo(wrapper);
        //判断查询结果是否为空,若为空,直接返回集合
        if (userInfos == null)
            return pageResult;
        List<TodayBest> todayBests = new ArrayList<>();
        for (UserInfo userInfo : userInfos) {
            TodayBest todayBest = new TodayBest();
            todayBest.setId(userInfo.getUserId());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
            todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
            todayBest.setAge(userInfo.getAge());
            //设置缘分值,遍历MongoDB中获取到的集合
            for (RecommendUser recommendUser : list) {
                if (recommendUser.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    todayBest.setFateValue(recommendUser.getScore().longValue());
                    break;
                }
            }
            todayBests.add(todayBest);
        }
        //排序
        todayBests.sort((o1, o2) -> (int) (o2.getFateValue() - o1.getFateValue()));
        pageResult.setItems(todayBests);
        return pageResult;
    }

    @Reference(version = "1.0.0")
    private VisitorsApi visitorsApi;

    //获取今日佳人的信息
    public TodayBest queryTodayBest(Long userId) {
        User user = UserThreadLocal.get();
        //保存访客记录
        Visitors visitors = new Visitors();
        visitors.setUserId(userId);//被访问者
        visitors.setVisitorUserId(user.getId());//来访用户
        visitorsApi.saveVisitor(visitors);
        UserInfo userInfo = userInfoService.queryUserInfoByUserId(userId);
        TodayBest todayBest = new TodayBest();
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
        todayBest.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
        todayBest.setAge(userInfo.getAge());
        double score = this.recommendUserService.queryScore(userId, user.getId());
        if(score == 0){
            score = 98; //默认分值
        }
        todayBest.setFateValue(new Double(score).longValue());
        return todayBest;
    }

    @Autowired
    private QuestionService questionService;

    public String queryQuestion(Long userId) {
        Question question = questionService.queryQuestion(userId);
        if (null != question) {
            return question.getTxt();
        }
        return "";
    }

    @Value("${tanhua.sso.url}")
    private String url;
    private static final ObjectMapper MAPPER = new ObjectMapper();
    @Autowired
    private RestTemplate restTemplate;
    public Boolean replyQuestion(Long userId, String reply) {
        User user = UserThreadLocal.get();
        UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(user.getId());

        //构建消息内容
        Map<String, Object> msg = new HashMap<>();
        msg.put("userId", user.getId().toString());
        msg.put("nickname", userInfo.getNickName());
        msg.put("strangerQuestion", queryQuestion(userId));
        msg.put("reply", reply);

        try {
            String msgStr = MAPPER.writeValueAsString(msg);

            String targetUrl = this.url + "/user/huanxin/messages";

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("target", userId.toString());
            params.add("msg", msgStr);

            HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, headers);

            ResponseEntity<Void> responseEntity = this.restTemplate.postForEntity(targetUrl, httpEntity, Void.class);

            return responseEntity.getStatusCodeValue() == 200;
        } catch (Exception e) {
            e.printStackTrace();
        }


        return false;
    }

    @Reference(version = "1.0.0")
    private UserLocationApi userLocationApi;

    public List<NearUserVo> queryNearUser(String gender, String distance) {
        User user = UserThreadLocal.get();
        //首先获取到自己的经纬度
        UserLocationVo userLocationVo = userLocationApi.queryByUserId(user.getId());
        Double longitude = userLocationVo.getLongitude();
        Double latitude = userLocationVo.getLatitude();
        List<UserLocationVo> userLocationVos = userLocationApi.queryUserFromLocation(longitude, latitude, Integer.valueOf(distance));
        if (CollectionUtils.isEmpty(userLocationVos))
            return Collections.emptyList();
        Set<Long> userIds = userLocationVos.stream().map(UserLocationVo::getUserId).collect(Collectors.toSet());
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(UserInfo::getUserId,userIds);
        //筛选条件
        if (StringUtils.equalsIgnoreCase(gender, "man")) {
            wrapper.eq(UserInfo::getSex, SexEnum.MAN);
        } else if (StringUtils.equalsIgnoreCase(gender, "woman")) {
            wrapper.eq(UserInfo::getSex, SexEnum.WOMAN);
        }
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(wrapper);
        ArrayList<NearUserVo> nearUserVos = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            //去除自己
            if (userInfo.getUserId().longValue() == user.getId().longValue())
                continue;
            NearUserVo nearUserVo = new NearUserVo();
            nearUserVo.setAvatar(userInfo.getLogo());
            nearUserVo.setNickname(userInfo.getNickName());
            nearUserVo.setUserId(userInfo.getUserId());
            nearUserVos.add(nearUserVo);
        }
        return nearUserVos;
    }

    //左滑右滑的用户列表
    public List<TodayBest> queryCardsList() {
        User user = UserThreadLocal.get();
        List<RecommendUser> recommendUserList = recommendUserService.queryRecommendation(user.getId(), 1, 50);
        if (CollectionUtils.isEmpty(recommendUserList)) {
            //默认推荐列表
            String[] ss = StringUtils.split(defaultRecommendUsers, ',');
            for (String s : ss) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(s));
                recommendUser.setToUserId(user.getId());
                recommendUserList.add(recommendUser);
            }
        }
        List<Long> idList = recommendUserList.stream().map(RecommendUser::getUserId).collect(Collectors.toList());
        Collections.shuffle(idList);
        int cnt = Math.min(10,idList.size());
        List<Long> result = idList.subList(0, cnt);
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(UserInfo::getUserId,idList);
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(wrapper);
        List<TodayBest> todayBestList = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            TodayBest todayBest = new TodayBest();
            todayBest.setId(userInfo.getUserId());
            todayBest.setAge(userInfo.getAge());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setGender(userInfo.getSex().name().toLowerCase());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
            todayBestList.add(todayBest);
        }
        return todayBestList;
    }

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Autowired
    private IMService imService;
    public boolean likeUser(Long likeUserId) {
        //1.执行喜欢逻辑
        Long userId = UserThreadLocal.get().getId();
        String result = userLikeApi.saveUserLike(userId, likeUserId);
        if (result == null)
            return false;
        //2.判断是否互相喜欢
        Boolean flag = userLikeApi.isMutualLike(userId, likeUserId);
        //互相喜欢,添加好友
        if (flag){
            imService.contactUser(likeUserId);
        }
        return true;
    }

    public void disLikeUser(Long likeUserId) {
        Long userId = UserThreadLocal.get().getId();
        userLikeApi.deleteUserLike(userId,likeUserId);
    }
}


